import { Mark, mergeAttributes } from "@tiptap/core";

declare module "@tiptap/core" {
  interface Commands<ReturnType> {
    bold: {
      setBold: () => ReturnType;
      unsetBold: () => ReturnType;
      toggleBold: () => ReturnType;
    };
  }
}

export const Bold = Mark.create({
  name: "bold",
  parseHTML() {
    return [
      {
        tag: "strong", // strong标签
      },
      {
        tag: "b", // b标签
        getAttrs: (node) => node.style.fontWeight !== "normal" && null,
      },
      {
        style: "font-weight=400",
        clearMark: (mark) => mark.type.name === this.name,
      },
      {
        style: "font-weight",
        getAttrs: (value) => /^(bold|bolder|[5-9]\d{2,})$/.test(value) && null,
      },
    ];
  },
  renderHTML({ HTMLAttributes }) {
    // mergeAttributes合并默认的HTMLAttributes和传入的HTMLAttributes
    return [
      "strong",
      mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
      0,
    ]; // 返回HTML结构
  },

  // 添加加粗相关的命令
  addCommands() {
    return {
      toggleBold:
        () =>
        ({ commands }) => {
          // 切换粗体
          return commands.toggleMark(this.name);
        },
      setBold:
        () =>
        ({ commands }) => {
          // 设置粗体
          return commands.setMark(this.name);
        },
      unsetBold:
        () =>
        ({ commands }) => {
          // 取消设置粗体
          return commands.unsetMark(this.name);
        },
    };
  },
  // 添加快捷键
  addKeyboardShortcuts() {
    return {
      "Mod-b": () => this.editor.commands.toggleBold(), // MacOS下使用Command键，Windows下使用Ctrl键
      "Mod-B": () => this.editor.commands.toggleBold()
    };
  },
});
